// Copyright 2016 Google LLC. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

#ifndef PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_
#define PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_

#include <list>
#include <map>
#include <memory>
#include <optional>
#include <vector>

#include <packager/file.h>
#include <packager/file/file_closer.h>
#include <packager/media/base/buffer_writer.h>
#include <packager/media/formats/mp2t/continuity_counter.h>
#include <optional>

namespace shaka {
namespace media {
namespace mp2t {

class PesPacket;
class ProgramMapTableWriter;

/// This class takes PesPackets, encapsulates them into TS packets, and write
/// the data to file. This also creates PSI from StreamInfo.
class TsWriter {
 public:
  explicit TsWriter(std::unique_ptr<ProgramMapTableWriter> pmt_writer);
  virtual ~TsWriter();

  /// This will fail if the current segment is not finalized.
  /// @param buffer to write segment data.
  /// @return true on success, false otherwise.
  virtual bool NewSegment(BufferWriter* buffer);

  /// Signals the writer that the rest of the segments are encrypted.
  virtual void SignalEncrypted();

  /// Add PesPacket to the instance. PesPacket might not be added to the buffer
  /// immediately.
  /// @param pes_packet gets added to the writer.
  /// @param buffer to write pes packet.
  /// @return true on success, false otherwise.
  virtual bool AddPesPacket(std::unique_ptr<PesPacket> pes_packet, BufferWriter* buffer);

 private:
  TsWriter(const TsWriter&) = delete;
  TsWriter& operator=(const TsWriter&) = delete;

  // True if further segments generated by this instance should be encrypted.
  bool encrypted_ = false;

  ContinuityCounter pat_continuity_counter_;
  ContinuityCounter elementary_stream_continuity_counter_;

  std::unique_ptr<ProgramMapTableWriter> pmt_writer_;
};

}  // namespace mp2t
}  // namespace media
}  // namespace shaka

#endif  // PACKAGER_MEDIA_FORMATS_MP2T_TS_WRITER_H_
